package com.xixi.utils;

import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

/**
 * 验证工具类 - 用于验证手机号和邮箱格式
 */
public class ValidatorUtil {

    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";

    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";

    private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);
    private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);

    public static boolean isValidPhone(String phone) {
        if (phone == null || phone.trim().isEmpty()) {
            return false;
        }
        return PHONE_PATTERN.matcher(phone.trim()).matches();
    }
    public static boolean isValidEmail(String email) {
        if (email == null || email.trim().isEmpty()) {
            return false;
        }
        return EMAIL_PATTERN.matcher(email.trim()).matches();
    }
    public static String validatePhoneWithDetail(String phone) {
        if (phone == null || phone.trim().isEmpty()) {
            return "手机号不能为空";
        }

        String trimmedPhone = phone.trim();

        if (trimmedPhone.length() != 11) {
            return "手机号必须是11位数字";
        }

        if (!trimmedPhone.startsWith("1")) {
            return "手机号必须以1开头";
        }

        char secondChar = trimmedPhone.charAt(1);
        if (secondChar < '3' || secondChar > '9') {
            return "手机号第二位必须是3-9之间的数字";
        }

        if (!PHONE_PATTERN.matcher(trimmedPhone).matches()) {
            return "手机号格式不正确";
        }

        return "手机号格式正确";
    }
    public static String validateEmailWithDetail(String email) {
        if (email == null || email.trim().isEmpty()) {
            return "邮箱地址不能为空";
        }

        String trimmedEmail = email.trim();

        if (!trimmedEmail.contains("@")) {
            return "邮箱地址必须包含@符号";
        }

        if (trimmedEmail.indexOf("@") != trimmedEmail.lastIndexOf("@")) {
            return "邮箱地址只能包含一个@符号";
        }

        String[] parts = trimmedEmail.split("@");
        if (parts.length != 2) {
            return "邮箱地址格式不正确";
        }

        String localPart = parts[0];
        String domainPart = parts[1];

        if (localPart.isEmpty()) {
            return "邮箱地址@前部分不能为空";
        }

        if (domainPart.isEmpty() || !domainPart.contains(".")) {
            return "邮箱地址域名格式不正确";
        }

        if (!EMAIL_PATTERN.matcher(trimmedEmail).matches()) {
            return "邮箱地址格式不正确";
        }

        return "邮箱地址格式正确";
    }
}
